//
//  QiyequanMineViewController.m
//  1243
//
//  Created by 洛水寒 on 16/5/26.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "QiyequanMineViewController.h"

#import "RecordsTableViewCell.h"//发布记录cell
#import "IncomeAndExpensesTableViewCell.h"//收支明细cell
#import "NetWorkTools.h"//网络请求
#import "RecordModel.h"//交易记录Model
#import "IncomeAndExpensesModel.h"//收支记录Model

@interface QiyequanMineViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *recordsTableView;
@property (nonatomic, strong) UITableView *incomeAndExpensesTableView;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *slider;//滑动条
@property (weak, nonatomic) IBOutlet UILabel *recordsLabel;//发布记录
@property (weak, nonatomic) IBOutlet UILabel *incomeAndExpensesLabel;//收支明细
@property (weak, nonatomic) IBOutlet UILabel *userName;

@property (weak, nonatomic) IBOutlet UILabel *userID;
@property (weak, nonatomic) IBOutlet UILabel *userNumber;
@property (weak, nonatomic) IBOutlet UILabel *value;

@end

@implementation QiyequanMineViewController
{
    NSMutableArray *_recordsDataArray;
    NSMutableArray *_incomeAndExpensesDataArray;
    
    NSString *_recordTotalCount;//发布记录数据数
    NSString *_incomeAndExpensesTotalCount;//收支明细数据数
    
    NSNotificationCenter *_nc;//通知中心
    
    BOOL _selected;
}


static NSString * const RecordsTableViewCellID = @"RecordsTableViewCell";
static NSString * const IncomeAndExpensesTableViewCellID = @"IncomeAndExpensesTableViewCell";

static NSString * const TableViewCellID = @"TableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"我";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //网络请求
    [self getUserData];
    
    _selected = NO;
    
    //设置ScrollView
    [self setScrollView];
    
    //初始化数据源
    [self createData];
    
    
    _nc = [NSNotificationCenter defaultCenter];
    //注册观察者 通知的名字一致
    [_nc addObserver:self selector:@selector(getRecordTotalCount) name:@"RecordTotalCount" object:nil];
    [_nc addObserver:self selector:@selector(getIncomeAndExpensesTotalCount) name:@"IncomeAndExpensesTotalCount" object:nil];

}

#pragma mark === 通知方法 ===
- (void)getRecordTotalCount{
    NSDictionary *dict = [ReadLoginData readLoginData];
    
    NSString *TradeUserId = [dict objectForKey:@"Number"];
    NSString *PageSize = _recordTotalCount;
    NSString *PageIndex = @"0";
    
    NSDictionary *params = @{
                              //
                              @"TradeUserId":TradeUserId,
                              @"PageSize":PageSize,
                              @"PageIndex":PageIndex
                              };
    
    [[NetWorkTools sharedNetWorkTools] OtherobjectWithURLDict:params AndMenthodName:@"MyPreRecord" completeBlock:^(id object) {
        //
        
        
        NSString *str = object[@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:str];
        
        
        for (NSDictionary *dict in arr) {
            RecordModel *model = [[RecordModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [_recordsDataArray addObject:model];
        }
        
        //刷新数据
        [_recordsTableView reloadData];
        
    }];
}

- (void)getIncomeAndExpensesTotalCount{
    NSDictionary *dict = [ReadLoginData readLoginData];
    
    NSString *TradeUserId = [dict objectForKey:@"Number"];
    NSString *PageSize = _incomeAndExpensesTotalCount;
    NSString *PageIndex = @"0";
    
    NSDictionary *params = @{
                              //
                              @"TradeUserId":TradeUserId,
                              @"PageSize":PageSize,
                              @"PageIndex":PageIndex
                              };
    
    [[NetWorkTools sharedNetWorkTools] OtherobjectWithURLDict:params AndMenthodName:@"MyPreRecord" completeBlock:^(id object) {
        //
        
        
        NSString *str = object[@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:str];
        
        
        for (NSDictionary *dic in arr) {
            IncomeAndExpensesModel *model = [[IncomeAndExpensesModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_incomeAndExpensesDataArray addObject:model];
        }
        
        //刷新数据
        [_incomeAndExpensesTableView reloadData];
        
    }];

}

#pragma mark === 网络请求 ===
- (void)getUserData{
    
    NSDictionary *dict = [ReadLoginData readLoginData];
    NSString *userNumber = [dict objectForKey:@"Number"];
    NSString *UserName = [dict objectForKey:@"UserName"];
    
    NSDictionary *params2 = @{
                              //
                              @"Id":userNumber,
                              @"UserName":UserName
                              };
    
    [[NetWorkTools sharedNetWorkTools] OtherobjectWithURLDict:params2 AndMenthodName:@"getUserInfo" completeBlock:^(id object) {
        //
        
        NSString *str = object[@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:str];
        if (arr == nil) {
            self.userName.text = @"";
            self.userID.text = @"";
            self.userNumber.text = @"";
            self.value.text = @"";
        }else{
            self.userName.text = [NSString stringWithFormat:@"%@",arr[0][@"RealName"]];
            self.userID.text = [NSString stringWithFormat:@"%@",arr[0][@"UserName"]];
            self.userNumber.text = [NSString stringWithFormat:@"%@",arr[0][@"TicketQty"]];
            self.value.text = [NSString stringWithFormat:@"%@",arr[0][@"TicketMoney"]];
        }
    }];
}

- (void)getRecord{
    
    NSDictionary *dict = [ReadLoginData readLoginData];
    
    NSString *TradeUserId = [dict objectForKey:@"Number"];
    NSString *PageSize = @"10";
    NSString *PageIndex = @"0";
    
    NSDictionary *params2 = @{
                              //
                              @"TradeUserId":TradeUserId,
                              @"PageSize":PageSize,
                              @"PageIndex":PageIndex
                              };
    
    [[NetWorkTools sharedNetWorkTools] OtherobjectWithURLDict:params2 AndMenthodName:@"MyPreRecord" completeBlock:^(id object) {
        //
        
        
        _recordTotalCount = [NSString stringWithFormat:@"%@", object[@"TotalCount"]];
        
        //创建通知 通知名字UserName
        NSNotification *totalCount = [[NSNotification alloc] initWithName:@"RecordTotalCount" object:nil userInfo:nil];
        
        //放在通知中心 发送出去
        [_nc postNotification:totalCount];
        
    }];

}

- (void)getIncomeAndExpenses{
    NSDictionary *dict = [ReadLoginData readLoginData];
    
    NSString *TradeUserId = [dict objectForKey:@"Number"];
    NSString *PageSize = @"10";
    NSString *PageIndex = @"0";
    
    NSDictionary *params2 = @{
                              //
                              @"TradeUserId":TradeUserId,
                              @"PageSize":PageSize,
                              @"PageIndex":PageIndex
                              };
    
    [[NetWorkTools sharedNetWorkTools] OtherobjectWithURLDict:params2 AndMenthodName:@"MyInAndEx" completeBlock:^(id object) {
        //
        
        _incomeAndExpensesTotalCount = [NSString stringWithFormat:@"%@", object[@"TotalCount"]];
        
        //创建通知 通知名字UserName
        NSNotification *totalCount = [[NSNotification alloc] initWithName:@"IncomeAndExpensesTotalCount" object:nil userInfo:nil];
        
        //放在通知中心 发送出去
        [_nc postNotification:totalCount];
        
    }];

}

#pragma mark === 设置ScrollView ===
- (void)setScrollView{
    //实际尺寸
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 2, SCREEN_HEIGHT - 238);
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;//按页滚动
    _scrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
}


- (void)createData{
    _recordsDataArray = [NSMutableArray array];
    _incomeAndExpensesDataArray = [NSMutableArray array];
    [self getRecord];
    [self getIncomeAndExpenses];
    
    //注册自定义cell
    [self.recordsTableView registerNib:[UINib nibWithNibName:@"RecordsTableViewCell" bundle:nil] forCellReuseIdentifier:RecordsTableViewCellID];
    [self.incomeAndExpensesTableView registerNib:[UINib nibWithNibName:@"IncomeAndExpensesTableViewCell" bundle:nil] forCellReuseIdentifier:IncomeAndExpensesTableViewCellID];
    
}


#pragma mark === TableViewDelegate ===
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        if (tableView == _recordsTableView) {
            return _recordsDataArray.count;
        }
        return _incomeAndExpensesDataArray.count;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _recordsTableView) {
        return 80;
    }
    return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //发布记录
    if (tableView == _recordsTableView) {
        RecordsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:RecordsTableViewCellID];
        
        RecordModel *model = _recordsDataArray[indexPath.row];
        
        NSString *tradeType = [NSString stringWithFormat:@"%@", model.TradeType];
        if ([tradeType isEqualToString:@"1"]) {
            cell.OfferStatus.text = @"发布购买";
        }else{
            cell.OfferStatus.text = @"发布出售";
        }
        cell.num.text = [NSString stringWithFormat:@"%@",model.ConfirmQty];
        cell.price.text = [NSString stringWithFormat:@"%@",model.TradePrice];
        cell.totalMoney.text = [NSString stringWithFormat:@"%@", model.PayMoney];
        cell.status.text = model.TradeStatusName;
        if ([model.TradeStatusName isEqualToString:@"关闭"]) {
            cell.status.textColor = [UIColor blackColor];
        }
        NSArray *arr = [model.TradeDate componentsSeparatedByString:@"T"];
        NSArray *arr1 = [arr[1] componentsSeparatedByString:@"."];
        
        cell.time.text = [NSString stringWithFormat:@"%@ %@", arr[0], arr1[0]];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
    //收支明细
    IncomeAndExpensesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IncomeAndExpensesTableViewCellID];
    
    IncomeAndExpensesModel *model = _incomeAndExpensesDataArray[indexPath.row];
    
    
    
    if ([model.TradeType intValue] == 2) {
        cell.status.text = @"出售";
        cell.priceOrBonus.textColor = [UIColor orangeColor];
        cell.priceOrBonus.text = [NSString stringWithFormat:@"+%@", model.PayMoney];
    }else{
        cell.status.text = @"购买";
        cell.priceOrBonus.textColor = [UIColor blackColor];
        cell.priceOrBonus.text = [NSString stringWithFormat:@"%@", model.PayMoney];
    }

    if ([model.PayType intValue] == 2) {
        cell.bonusString.text = @"积分";
    }
    NSArray *arr = [model.TradeDate componentsSeparatedByString:@"T"];
    NSArray *arr1 = [arr[1] componentsSeparatedByString:@"."];
    
    cell.time.text = [NSString stringWithFormat:@"%@ %@", arr[0], arr1[0]];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}


#pragma mark === ScrollViewDelegate ===
//滚动中
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == _scrollView) {
        _slider.frame = CGRectMake(20 + (scrollView.contentOffset.x - 20) / 2, _incomeAndExpensesLabel.frame.origin.y + 47, (SCREEN_WIDTH - 40) / 2, 3);
        
        if (scrollView.contentOffset.x > SCREEN_WIDTH / 2) {
            _selected = YES;
            _incomeAndExpensesLabel.textColor = [UIColor blackColor];
            _recordsLabel.textColor = [UIColor lightGrayColor];
        }else {
            _selected = NO;
            _recordsLabel.textColor = [UIColor blackColor];
            _incomeAndExpensesLabel.textColor = [UIColor lightGrayColor];
        }
    }
}

#pragma mark === 点击发布记录 ===
- (IBAction)clickRecord:(id)sender {
    if (_selected == YES) {
        _recordsLabel.textColor = [UIColor blackColor];
        _incomeAndExpensesLabel.textColor = [UIColor lightGrayColor];
        
        [UIView animateWithDuration:0.2 animations:^{
            _slider.frame = CGRectMake(10, _recordsLabel.frame.origin.y + 47, _recordsLabel.frame.size.width - 20, 3);
        }];
        
        [UIView animateWithDuration:0.2 animations:^{
            _scrollView.contentOffset = CGPointZero;
        }];
        
    }
    _selected = NO;
}

#pragma mark === 点击收支明细 ===
- (IBAction)clickIncomeAndExpense:(id)sender {
    if (!_selected) {
        _incomeAndExpensesLabel.textColor = [UIColor blackColor];
        _recordsLabel.textColor = [UIColor lightGrayColor];
        
        [UIView animateWithDuration:0.2 animations:^{
            _slider.frame = CGRectMake(10 + _incomeAndExpensesLabel.frame.origin.x, _incomeAndExpensesLabel.frame.origin.y + 47, _incomeAndExpensesLabel.frame.size.width - 20, 3);
        }];
        [UIView animateWithDuration:0.2 animations:^{
            _scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0 );
        }];
    }
    _selected = YES;
}



- (UITableView *)recordsTableView{
    if (!_recordsTableView) {
        
        _recordsTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,-35, SCREEN_WIDTH, SCREEN_HEIGHT - 166)style:UITableViewStyleGrouped];
        _recordsTableView.delegate = self;
        _recordsTableView.dataSource = self;
        _recordsTableView.separatorColor = [UIColor clearColor];
        _recordsTableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [_scrollView addSubview:_recordsTableView];
        
        
    }
    return _recordsTableView;
}

- (UITableView *)incomeAndExpensesTableView{
    if (!_incomeAndExpensesTableView) {
        
        _incomeAndExpensesTableView = [[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH,-35, SCREEN_WIDTH, SCREEN_HEIGHT - 166)style:UITableViewStyleGrouped];
        _incomeAndExpensesTableView.delegate = self;
        _incomeAndExpensesTableView.dataSource = self;
        _incomeAndExpensesTableView.separatorColor = [UIColor clearColor];
        _incomeAndExpensesTableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [_scrollView addSubview:_incomeAndExpensesTableView];
        
        
    }
    return _incomeAndExpensesTableView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
